
# import requests_cache
import numpy
import pytz
from datetime import datetime

import os, sys
try:
    import yfinance as yahoo
except ModuleNotFoundError:
    # print("yfinance is not installed via system packages.")
    # sys.path.append(os.path.abspath('venv/lib/python3.12/site-packages'))
    sys.path.append(os.path.abspath('deps/yfinance'))
    sys.path.append(os.path.abspath('deps/peewee'))
    sys.path.append(os.path.abspath('deps/multitasking'))
import yfinance as yahoo

def get_stonk_price(ticker, std_market_only = False):
    stonk      = yahoo.Ticker(ticker)
    last_close = stonk.info["previousClose"]
    current    = stonk.info["currentPrice"]
    delta      = round(current - last_close, 2)
    delta_pct  = round((delta/last_close) * 100, 2)

    print("%s @ $%.2f (%.2f, %.2f%%)" % 
        (ticker, current, delta, delta_pct))
    data = stonk.history(
        period="1d", interval="1m", prepost=(not std_market_only))

    eastern      = pytz.timezone('US/Eastern')
    current_time = datetime.now(eastern)
    mkt_close = current_time.replace(
        hour=16, minute=0, second=0, microsecond=0)
    mkt_open  = current_time.replace(
        hour= 9, minute=0, second=0, microsecond=0)
    if current_time > mkt_close or current_time < mkt_open:
        price_nonstd = data.iloc[-1,3]
        if current_time > mkt_close:
            msg = "Post-market session: $%.2f"
        if current_time < mkt_open:
            msg = "Pre-market session: $%.2f"
        print(msg % price_nonstd)
    return data

def invoke_from_c(ticker=None):
    if ticker == None:
        ticker = input("Enter a ticker:" )
    stonk = yahoo.Ticker(ticker)
    dataframe = stonk.history(
        period="1mo", interval="1h", prepost=False)
    timestamps = [t.timestamp() for t in dataframe.index]
    # return dataframe.to_numpy().astype(numpy.float32)
    df = dataframe.to_numpy()
    # print("where does this get printed?")
    return numpy.column_stack( (timestamps, df[:,0:]) )

if __name__ == "__main__":
    def main():
        t = str()
        # 0 = script name
        if len(sys.argv) < 2:
            t = input("Enter a ticker: ")
        else:
            invoke_from_c()
            return
        dataframe = get_stonk_price(t)
        print(dataframe)
        # display column names as a list
        print(dataframe.columns.tolist())
        dataframe.to_csv("%s.csv" % t)

    main()

